<?php


namespace App\Utils;


use App\Facade\AppContext;
use Illuminate\Support\Facades\Request;
use Throwable;

/**
 * es 日志
 * Class ElasticLog
 * @package App\Utils
 */
class ElasticLog
{

    /**
     * @param \Illuminate\Http\Request $request
     * @param Throwable $exception
     */
    public static function error($request, $exception)
    {

        $data = [
            'method' => $request->method(),
            'url' => $request->fullUrl(),
            'route' => $request->route(),
            'clientip' => $request->ip(),
            'params' => $request->all(),
            'logdate' => time(),
            'message' => $exception->getMessage(),
            'error_class' => get_class($exception),
            'trace' => $exception->getTraceAsString()
        ];
        $user_id = 0;
        try {
            $user_id = AppContext::userId();
        } catch (Throwable $exception) {

        }
        $data['user_id'] = $user_id;
        $dir = storage_path('logs' . DIRECTORY_SEPARATOR . 'framework-error');
        self::write($dir, json_encode($data));
    }

    /**
     * @param $response
     * @param $request
     */
    public static function fail($response)
    {
        $request = Request::instance();
        $data = [
            'method' => $request->method(),
            'url' => $request->fullUrl(),
            'route' => $request->route(),
            'clientip' => $request->ip(),
            'params' => $request->all(),
            'logdate' => time(),
            'response' => $response
        ];
        $user_id = 0;
        try {
            $user_id = AppContext::userId();
        } catch (Throwable $exception) {

        }
        $data['user_id'] = $user_id;
        $dir = storage_path('logs' . DIRECTORY_SEPARATOR . 'request-error');
        self::write($dir, json_encode($data));
    }

    /**
     * 写入日志
     * @param $dir
     * @param string $data 写入内容
     * @return bool
     */
    private static function write($dir, $data)
    {
        try {
            self::create_dir($dir);
            $file = $dir . DIRECTORY_SEPARATOR . date('Ymd') . '.log';
            if(!$fp=@fopen($file,"a")){
                return false;
            }
            if(!fwrite($fp, "$data\r\n"))
                return false;
            fclose($fp);
            chmod($file, 0777);
        } catch (Throwable $e) {
            //写入失败不处理避免造成业务错误
        }
        return false;
    }

    /**
     * 写入日志
     * @param $dir
     * @param int $mode
     * @return bool
     */
    private static function create_dir($dir, $mode = 0777)
    {
        return is_dir($dir) or (self::create_dir(dirname($dir)) and mkdir($dir, $mode));
    }
}